package com.easy.activiti.controller;

import com.easy.activiti.util.AjaxResponse;
import com.easy.activiti.listener.EventHandler;
import com.easy.activiti.util.GlobalConfig;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author zhouchuang
 * 2024-11-04 21:59:39
 */

@RestController
@RequestMapping("/activiti")
public class ActivitiController {

    @Autowired
    private ProcessRuntime processRuntime;

    @PreAuthorize("hasAnyRole('ACTIVITI_USER','ACTIVITI_ADMIN')")
    @PostMapping(value = "/startProcess")
    public AjaxResponse startProcess(@RequestParam("processDefinitionKey") String processDefinitionKey,
                                     @RequestParam("instanceName") String instanceName,
                                     @RequestParam("businessKey") String businessKey) {
        try {
            ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                    .start()
                    .withProcessDefinitionKey(processDefinitionKey)
                    .withName(instanceName)
                    .withBusinessKey(businessKey)
                    .withVariables((Map<String, Object>) EventHandler.Context.get(processDefinitionKey+"startVariables").execute(businessKey))
                    .build());
            return AjaxResponse.AjaxData(GlobalConfig.ResponseCode.SUCCESS.getCode(),
                    GlobalConfig.ResponseCode.SUCCESS.getDesc(), processInstance.getName()+"；"+processInstance.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResponse.AjaxData(GlobalConfig.ResponseCode.ERROR.getCode(),
                    "创建流程实例失败", e.toString());
        }
    }
}
